package yunquan.wang.modules.base.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import yunquan.wang.base.dao.DaoUtils;
import yunquan.wang.base.dao.springdata.BaseRepository;
import yunquan.wang.base.service.impl.BaseServiceImpl;
import yunquan.wang.modules.base.dao.AuthorityDao;
import yunquan.wang.modules.base.dao.RolesAuthorityDao;
import yunquan.wang.modules.base.dao.RolesinfoDao;
import yunquan.wang.modules.base.dao.RulesInfoDao;
import yunquan.wang.modules.base.entity.Authority;
import yunquan.wang.modules.base.entity.RolesAuthority;
import yunquan.wang.modules.base.entity.Rolesinfo;
import yunquan.wang.modules.base.entity.RulesInfo;
import yunquan.wang.modules.base.service.RolesinfoService;
/**
 *  Rolesinfo Service层 实现
 *  @author 王云权  wangyunquan@gmail.com
 *  用生成器 生成于 2011-09-30 22:37
 *
 */
@Service("rolesinfoService")
@Transactional(value="jpaTransaction")
public class RolesinfoServiceImpl extends BaseServiceImpl<Rolesinfo>
		implements RolesinfoService {
	@Resource
	private RolesinfoDao rolesinfoDao;
	@Resource
	private RolesAuthorityDao rolesAuthorityDao;
	@Resource
	private AuthorityDao  authorityDao;
	@Resource
	private RulesInfoDao  rulesInfoDao;
	 
 

	public BaseRepository<Rolesinfo, String> getDao() {
		return rolesinfoDao;
	}

	@Override
	/**
	 * 清除掉指定Key缓存
	 */
	@CacheEvict (value="securityCache", key="#roleId + 'securityCache'")
	public void saveAuthAndRules(String roleId,
			Map<String, Set<String>> authAndRules) {
	Rolesinfo role=	rolesinfoDao.findOne(roleId);
	//删除原来的
	 @SuppressWarnings("unchecked")
	List<RolesAuthority>  oldAuth=	rolesAuthorityDao.findAll( DaoUtils.eq("rolesinfo.id", roleId));
	 rolesAuthorityDao.delete(oldAuth);
	
	for(Entry<String, Set<String>>  entry:authAndRules.entrySet())
	{
		RolesAuthority rolesAuthority=new RolesAuthority();
		Authority auth=authorityDao.findOne(entry.getKey());
		Set<RulesInfo> rulesInfos=new HashSet<RulesInfo>();
		for(String rule:entry.getValue())
		{
			//如果是全部，则为空，不做处理
			if(StringUtils.isNotBlank(rule))
			{
		   RulesInfo rulesInfo=	rulesInfoDao.findOne(rule);
		     rulesInfos.add(rulesInfo);
			}
		}
		rolesAuthority.setAuthority(auth);
		rolesAuthority.setRolesinfo(role);
		if(rulesInfos.size()!=0)
		rolesAuthority.setRulesInfos(rulesInfos);
		rolesAuthorityDao.save(rolesAuthority);
	}

	}


}
